package pt.mleiria.security.login;

import java.security.Principal;
import java.security.acl.Group;
import java.util.ArrayList;
import java.util.Enumeration;

import javax.security.auth.login.LoginException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.MDC;
import org.jboss.security.auth.spi.DatabaseServerLoginModule;

/**
 * @author NB13712
 * 
 */
public class CryptoDatabaseServerLoginModule extends DatabaseServerLoginModule {

	private static Log LOG = LogFactory.getLog("pt.mleiria.security.login");

	@Override
	public boolean login() throws LoginException {
		String username = null;
		ArrayList<String> roles = new ArrayList<String>();
		try {
			boolean successfulLogin = super.login();
			username = super.getUsername();
			MDC.put("context", null + "," + username + "," + null);

			if (successfulLogin) {
				Group[] roleSets = super.getRoleSets();

				for (Group group : roleSets) {
					for (Enumeration<Principal> e = (Enumeration<Principal>) group.members(); e.hasMoreElements();) {
						roles.add(e.nextElement().getName());
					}
				}

				StringBuffer sb = new StringBuffer();
				sb.append("Utilizador " + username
						+ " autenticou-se com sucesso.Roles associados: ");
				for (int i = 0; i < roles.size(); i++) {
					sb.append(roles.get(i));
					if (i != (roles.size() - 1))
						sb.append(","); // in the last element, don't append the ","
				}
				String logString = sb.toString();
				LOG.info(logString);
				return true;
			}

			LOG.info("Utilizador " + username
					+ " tentou autenticar-se sem sucesso");
			return false;
		}

		catch (LoginException e) {
			/*
			 * super.getUsername is repeated in the next lines because it's only
			 * available after super.login(), but the method might fail before
			 * the line username = super.getUsername().
			 */
			MDC.put("context", null + "," + super.getUsername() + "," + null);
			LOG.info("Utilizador " + super.getUsername()
					+ " tentou autenticar-se sem sucesso");
			throw e;
		}

		finally {
			MDC.remove("context");
		}

	}

}
